<?php


function replaceImgUrl($title)
{
    $pattern = '/<img.*?src="(.*?)".*?>/i';
    $title   = preg_replace_callback($pattern, function ($matches) {
        $full = $matches[0];
        if (!empty($matches[1])) {
            return str_replace($matches[1], cdnurl($matches[1], true), $full);
        }

        $url      = $matches[1];
        $host     = parse_url($url, PHP_URL_HOST);
        $cdn_host = parse_url(cdnurl('', true), PHP_URL_HOST);
        if ($host) {
            if ($host != $cdn_host) {
                $url = str_replace($host, $cdn_host, $url);
            }
        } else {
            $url = cdnurl($url, true);
        }

        // ddd($matches);
        return '<img src="' . $url . '">';
    }, $title);
    return $title;
}

/**
 * 计算倒计时天数
 *
 * @param int $targetTimestamp 目标时间戳
 * @param int|null $currentTimestamp 当前时间戳（可选，默认为当前时间）
 * @return int 剩余天数（目标时间已过则返回 0）
 */
function countdownDays(int $targetTimestamp, ?int $currentTimestamp = null): int
{
    // 获取当前时间戳（如果未提供）
    $current = $currentTimestamp ?? time();

    // 如果目标时间已过，返回 0
    if ($targetTimestamp <= $current) {
        return 0;
    }

    // 计算剩余秒数
    $remainingSeconds = $targetTimestamp - $current;

    // 计算剩余天数（向上取整）
    return ceil($remainingSeconds / 86400);
}




/**
 * 刷题题目信息数据处理  
 * @param mixed $list
 * @param mixed $questionUserAnswers用户答案
 * @param mixed $recordUser 是否返回用户答案
 * @return void
 */
if (!function_exists('getQuestionArray')) {
    function getQuestionArray($list, $questionUserAnswers = [], $recordUser = false)
    {
        if (empty($list)) {
            return;
        }
        foreach ($list as &$item) {
            // 跳过拍照题的处理，因为拍照题没有选项等数据
            if (isset($item['kind']) && $item['kind'] === 'PHOTO') {
                continue;
            }
            
            // 解析选项JSON和图片
            $options = !empty($item['options_json']) ? json_decode($item['options_json'], true) : [];
            $optionImages = [];
            if (!empty($item['options_img'])) {
                foreach (json_decode($item['options_img'], true) as $image) {
                    $optionImages[$image['key']] = $image['value'];
                }
            }
            // 解析正确答案
            $correctAnswers = parseAnswer($item['answer'], $item['kind']);
            // 构建完整选项数据
            $item['options_json'] = buildOptions($options, $optionImages, $correctAnswers);
            unset($item['options_img']);
            // 填空题和主观题处理
            if ($item['kind'] === 'FILL') {
                $item['answer'] = processFillAnswer($item['answer']);
            } elseif ($item['kind'] === 'SHORT') {
                $item['answer'] = processShortAnswer($item['answer']);
            }
            # 刷题用户答案
            if ($recordUser) { # 判定是否需要查询用户答案
                # 查询用户答题信息
                if (!empty($questionUserAnswers) && isset($questionUserAnswers[$item['question_id']])) {
                    $userAnswer = $questionUserAnswers[$item['question_id']];
                    if ($item['kind'] === 'MULTI') {
                        # 这个对选题是没有使用英文“,”分割的
                        // $item['user_answer'] = preg_split('//u', $userAnswer['answer'], -1, PREG_SPLIT_NO_EMPTY);
                        $item['user_answer'] = explode(',', $userAnswer['answer']);
                    } elseif ($item['kind'] === 'FILL') {
                        $item['user_answer'] = explode('|||', $userAnswer['answer']);
                    } elseif ($item['kind'] === 'SHORT') {
                        # 主观题
                        $item['user_answer'] = ['answer' => $userAnswer['answer'], 'imgs' => $userAnswer['imgs']];
                    } else {
                        $item['user_answer'] = $userAnswer['answer'];
                    }
                    $item['is_right'] = $userAnswer['is_right'];
                    $item['question_user_answers_id'] = $userAnswer['question_user_answers_id'];
                } else {
                    $item['user_answer'] = '';
                    $item['is_right'] = -1; // -1 表示未答题
                }
            }
        }
        return $list;
    }
}









/**
 * 解析正确答案
 */
function parseAnswer($answer, $kind)
{
    if ($kind === 'MULTI') {
        return explode(',', $answer);
    }
    return [$answer];
}

/**
 * 构建完整选项结构
 * 单选 多选 判断
 */
function buildOptions($options, $optionImages, $correctAnswers)
{
    $result = [];
    foreach ($options as $key => $text) {
        $result[] = [
            'key' => $key,
            'text' => $text,
            'image' => $optionImages[$key] ?? '',
            'is_correct' => in_array($key, $correctAnswers, true)
        ];
    }
    return $result;
}
/**
 * 处理填空题答案
 */
function processFillAnswer($answer)
{
    $answers = json_decode($answer, true);
    return [
        'answers' => $answers,
        'blank_count' => is_array($answers) ? count($answers) : 0
    ];
}
/**
 * 处理主观题答案
 */
function processShortAnswer($answer)
{
    return [
        'sample_answer' => json_decode($answer, true)
    ];
}

# 随机题 识别每道题分数
if (!function_exists('getSingleScore')) {
    /**
     * 试卷不同类型或难度题的分数
     * @param $configs
     * @param $kind
     * @param $difficulty
     * @return mixed
     */
    function getSingleScore($configs, $kind, $difficulty)
    {
        $config = $configs[$kind];

        if ($config['use_difficulty'] && !empty($config['difficulty'][$difficulty]) && !empty($config['difficulty'][$difficulty]['score'])) {
            return $config['difficulty'][$difficulty]['score'];
        }

        return $config['score'];
    }
}
